<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/11
 * Time: 17:43
 */

namespace App\CronTask;


use App\Enums\UrlEnums;
use App\Library\Auth;
use App\Utility\Pool\MysqlObject;
use App\Utility\Pool\MysqlPool;
use EasySwoole\EasySwoole\Crontab\AbstractCronTask;
use EasySwoole\HttpClient\HttpClient;
use EasySwoole\MysqliPool\Mysql;

/**
 * 更新比赛直播链接
 * Class LiveVideoCron
 * @package App\CronTask
 */
class LiveVideoCron extends AbstractCronTask
{
    public static function getRule(): string
    {
        // TODO: Implement getRule() method.
        return '* */1 * * *';
    }

    public static function getTaskName(): string
    {
        // TODO: Implement getTaskName() method.
        // 定时任务名称
        return 'live_video';
    }

    static function run(\swoole_server $server, int $taskId, int $fromWorkerId, $flags = null)
    {
        // TODO: Implement run() method.

        $tables = ['siam_lolmatchs','siam_dotamatchs'];
        $path = [UrlEnums::LOL_LIVE_VIDEO_PATH,UrlEnums::DOTA_LIVE_VIDEO_PATH];
        $games = ['lol','dota'];

        for( $i=0;$i<count($path);$i++ ){
            MysqlPool::invoke(function (MysqlObject $db)use($tables,$games,$path,$i){
                $match_ids = $db->getColumn($tables[$i],'match_id');
                foreach ( $match_ids as $match_id ){
                    $url = UrlEnums::FJURL.$path[$i]."?match_id={$match_id}&version=2";
                    $client = new HttpClient($url);
                    list($s1, $s2) = explode(' ', microtime());
                    $microtime = (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000); //毫秒时间戳
                    $option = [
                        'path'      => $path[$i],
                        'api_time'  => $microtime
                    ];
                    $header = Auth::getInstance()->header($option);
                    $client->setHeaders($header,true,false);
                    $response = $client->get();
                    $content = $response->getBody();

                    $data = json_decode($content,true);
                    if( isset($data['code']) && $data['code'] == 200 && $data['data'] ){
                        foreach ( $data['data'] as $item ){
                            if( isset($item['url']) ){
                                $video = $db->where('game',$games[$i])->where('url',$item['url'])->where('name',$item['name'])->where('match_id',$match_id)->getOne('siam_live_video');
                                if( !$video ){
                                    $item['game'] = $games[$i];
                                    $item['match_id'] = $match_id;
                                    $res = $db->insert('siam_live_video',$item);
                                }
                            }

                        }
                    }
                }
            });
        }
    }
}